package com.ftl.search.repository;

import com.ftl.search.model.QueryDefinition;
import com.ftl.search.model.RestConfigDefinition;
import com.ftl.search.model.RestQueryDefinition;
import com.ftl.search.model.SearchDefinition;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.*;

@Component
public class InMemorySearchDefinitionRepository implements SearchDefinitionWriter {

    /**
     * ES 相关查询配置
     */
    private final Map<String, QueryDefinition> searches = Collections.synchronizedMap(new LinkedHashMap<>());
    /**
     * ES 多实体查询模板
     */
    private final Map<String, Set<String>> templates = Collections.synchronizedMap(new LinkedHashMap<>());

    /**
     * Rest 相关网站配置
     */
    private final Map<String, RestConfigDefinition> restMapping = Collections.synchronizedMap(new LinkedHashMap<>());
    /**
     * Rest 相关查询模板配置
     */
    private final Map<String, RestQueryDefinition> restTemplates = Collections.synchronizedMap(new LinkedHashMap<>());

    @Override
    public void save(SearchDefinition query) {
        if (!ObjectUtils.isEmpty(query)) {
            if (!ObjectUtils.isEmpty(query.getMapping())) {
                this.searches.clear();
                this.searches.putAll(query.getMapping());
            }
            if (!ObjectUtils.isEmpty(query.getTemplate())) {
                this.templates.clear();
                this.templates.putAll(query.getTemplate());
            }
            if (!ObjectUtils.isEmpty(query.getRestMapping())) {
                this.restMapping.clear();
                this.restMapping.putAll(query.getRestMapping());
            }
            if (!ObjectUtils.isEmpty(query.getRestTemplate())) {{
                this.restTemplates.clear();
                this.restTemplates.putAll(query.getRestTemplate());
            }}
        }
    }

    @Override
    public Map<String, QueryDefinition> getSearches() {
        return this.searches;
    }

    @Override
    public Map<String, Set<String>> getTemplates() {
        return this.templates;
    }

    @Override
    public Map<String, RestConfigDefinition> getRestMapping() {
        return this.restMapping;
    }

    @Override
    public Map<String, RestQueryDefinition> getRestTemplates() {
        return this.restTemplates;
    }
}
